package stark.app.frame.document.poiexcel;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.CellInfo;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.IFormat;
import com.bin.david.form.data.format.grid.BaseGridFormat;
import com.bin.david.form.data.format.selected.BaseSelectFormat;
import com.bin.david.form.data.table.FormTableData;
import com.bin.david.form.data.table.TableData;
import com.bin.david.form.utils.DensityUtils;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

import stark.app.R;

/**
 * implementation 'com.github.huangyanbin:SmartTable:2.2.0'
 */

public class ExcelDemoActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "ExcelDemoActivity";
    private SmartTable<Form> mTable;
    EditText mEtInput;
    private Form selectForm;
    String mFilePath;
    Form[][] mForms;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_excel_demo);
        mTable = findViewById(R.id.table);
        int dp5 = DensityUtils.dp2px(this, 40);
        int dp10 = DensityUtils.dp2px(this, 10);
        mTable.getConfig().setHorizontalPadding(dp5).setVerticalPadding(dp10);

        mFilePath = getIntent().getStringExtra("FilePath");
        mForms = onReadFile(mFilePath);
        setTableData();

        mEtInput = findViewById(R.id.edit_in);
        findViewById(R.id.btnUpdate).setOnClickListener(this);
        findViewById(R.id.btnSave).setOnClickListener(this);
    }

    public Form[][] onReadFile(String path) {
        Form[][] forms = new Form[100][26];
        try {
            FileInputStream fis = new FileInputStream(new File(path));
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            XSSFSheet sheet = workbook.getSheetAt(0);
            int rowsCount = sheet.getPhysicalNumberOfRows();
            Log.e(TAG, "onReadClick: " + rowsCount);
            FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
            for (int r = 0; r < rowsCount; r++) {
                Row row = sheet.getRow(r);
                int cellsCount = row.getPhysicalNumberOfCells();
                for (int c = 0; c < cellsCount; c++) {
                    String value = getCellAsString(row, c, formulaEvaluator);
                    String cellInfo = "r:" + r + "; c:" + c + "; v:" + value;
                    forms[r][c] = new Form(value);
                    Log.e(TAG, "onReadClick: " + cellInfo);
                }
            }
        } catch (Exception e) {
            Log.e("TAG", "onReadClick: " + e.toString());
        }
        return forms;
    }

    protected String getCellAsString(Row row, int c, FormulaEvaluator formulaEvaluator) {
        String value = "";
        try {
            Cell cell = row.getCell(c);
            CellValue cellValue = formulaEvaluator.evaluate(cell);
            switch (cellValue.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    value = "" + cellValue.getBooleanValue();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    double numericValue = cellValue.getNumberValue();
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        double date = cellValue.getNumberValue();
                        SimpleDateFormat formatter =
                                new SimpleDateFormat("dd/MM/yy");
                        value = formatter.format(HSSFDateUtil.getJavaDate(date));
                    } else {
                        value = "" + numericValue;
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    value = "" + cellValue.getStringValue();
                    break;
                default:
            }
        } catch (NullPointerException e) {
        }
        return value;
    }

    private void setTableData() {
        final FormTableData<Form> tableData = FormTableData.create(mTable, "mySheet", 26, mForms);
        tableData.setFormat(new IFormat<Form>() {
            @Override
            public String format(Form form) {
                if (form != null) {
                    return form.getName();
                } else {
                    return "";
                }
            }
        });
        mTable.setSelectFormat(new BaseSelectFormat());
        tableData.setOnItemClickListener(new TableData.OnItemClickListener<Form>() {
            @Override
            public void onClick(Column column, String value, Form form, int col, int row) {
                if (form != null) {
                    selectForm = form;
                    mEtInput.setFocusable(true);
                    mEtInput.setFocusableInTouchMode(true);
                    mEtInput.requestFocus();
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                }

            }

        });
        mTable.getConfig().setTableGridFormat(new BaseGridFormat() {
            @Override
            protected boolean isShowHorizontalLine(int col, int row, CellInfo cellInfo) {
                if (row == tableData.getLineSize() - 1) {
                    return false;
                }
                return true;
            }

            @Override
            protected boolean isShowVerticalLine(int col, int row, CellInfo cellInfo) {
                if (row == tableData.getLineSize() - 1) {
                    return false;
                }
                return true;
            }
        });
        mTable.setTableData(tableData);
    }

    public void onWriteExcel() {
        OutputStream outputStream = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(mFilePath);
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            XSSFSheet sheet = workbook.getSheetAt(0);
            for (int i = 0; i < mForms.length; i++) {
                Row row = sheet.getRow(i);
                for (int j = 0; j < mForms[i].length; j++) {
                    Cell cell = row.getCell(j);
                    cell.setCellValue(mForms[i][j].getName());
                }
            }
            outputStream = new FileOutputStream(mFilePath);
            workbook.write(outputStream);
        } catch (Exception e) {
            Log.e(TAG, "onWriteExcel: " + e.toString());
        } finally {
            try {
                if (outputStream != null) outputStream.close();
                if (fis != null) fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btnUpdate) {
            if (selectForm != null) {
                selectForm.setName(mEtInput.getText().toString());
                mTable.invalidate();
                mEtInput.setText("");
            }
        } else if (id == R.id.btnSave) {
            onWriteExcel();
        }
    }
}